package com.qinyh.activity;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.qinyh.entity.BookMark;
import com.qinyh.util.CRDBHelper;
import com.qinyh.util.DateUtil;
import com.qinyh.util.DebugUtil;
import com.qinyh.util.TemplateStore;
import com.qinyh.util.TextSplitUtil;
import com.qinyh.view.MyProgressDialog;
import com.qinyh.view.MyProgressDialog.MyProgresDialogCallBack;
import com.qinyh.view.PageView;

public class PageActivity extends Activity {
	/** 用于设置读书背景的请求代码 */
	private final int REQUEST_CODE_SET_BAGKGROUD = 10;

	/** 用于设置字体相关的请求代码 */
	private final int REQUEST_CODE_SET_FONT = 11;

	/** dialog id */
	private final int SAVEBOOKMARKSUCCESS = 11;
	private final int SAVEBOOKMARKFAIL = 12;
	private static final int CHANGEFONT = Menu.FIRST;
	private static final int NOTE = Menu.FIRST + 3;
	private static final int SAVEBOOKMARK = Menu.FIRST + 4;
	// 旋屏菜单
	private static final int CIRC_SCREEN = Menu.FIRST + 9;
	// private static final int BACK = Menu.FIRST + 6;
	private static final int SKIP = Menu.FIRST + 15;
	private static final int EXIT = Menu.FIRST + 7;
	private static final int ABOUT = Menu.FIRST + 8;

	// 查看书签
	private static final int VIEWBOOKMARK = Menu.FIRST + 20;

	private PageView pageView;
	private CRDBHelper mHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.pagelayout);
		setTitle(TemplateStore.getCurrentChapter().getChapterName());
		pageView = (PageView) findViewById(R.id.page);
		pageView.activity = this;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(1, CHANGEFONT, 0, R.string.changefont).setShortcut('3', 'a')
				.setIcon(R.drawable.setfont);
		menu.add(1, NOTE, 1, R.string.note).setShortcut('3', 'c')
				.setIcon(R.drawable.text32);
		menu.add(2, SAVEBOOKMARK, 2, R.string.savebookmark)
				.setShortcut('3', 'd').setIcon(R.drawable.addbookmark);
		menu.add(2, VIEWBOOKMARK, 3, R.string.viewbookmark)
				.setShortcut('3', 'q').setIcon(R.drawable.viewbookmark);
		// 旋转屏幕菜单
		/*menu.add(2, CIRC_SCREEN, 3, R.string.circumgyrate)
				.setShortcut('3', 'c').setIcon(R.drawable.circscreen);*/

		menu.add(2, SKIP, 5, R.string.gotopage).setShortcut('3', 'x')
				.setIcon(R.drawable.uponelevel);
		// menu.add(3, EXIT, 6, R.string.exit).setShortcut('3', 'e')
		// .setIcon(R.drawable.close);
		// menu.add(3, ABOUT, 7, R.string.about).setShortcut('3', 'o')
		// .setIcon(android.R.drawable.star_big_on);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case CHANGEFONT:// change text size
			// 设置字体相关
			alertSetting();
			return true;
		case NOTE:// change background image
			// Intent ix = new Intent(getApplicationContext(),
			// ImageBrowser.class);
			// startActivity(ix);
			// startActivityForResult(ix, REQUEST_CODE_SET_BAGKGROUD);
			this.openContextMenu(pageView);
			return true;

		case CIRC_SCREEN:// 触发了旋屏菜单
			circumgyrateScreen();
			return true;

		case SAVEBOOKMARK:// save book mark
			saveBookMarkDialog();
			return true;
		case VIEWBOOKMARK:// 浏览书签
			bookMarkView();
			return true;

		case EXIT:// exit system
			this.finish();
			return true;
		case SKIP:// 去页
			ProgressDialog dialog = buildDialog4(this);
			dialog.show();
			return true;
		case ABOUT:// about this software
			showDialog(ABOUT);
			return true;
		default:
			return true;
		}
	}

	private ProgressDialog buildDialog4(Context context) {
		MyProgressDialog dialog = new MyProgressDialog(context);
		dialog.setTitle("去页:");
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setIcon(R.drawable.webtext);
		dialog.setMax(100);
		int start = TemplateStore.getCurrentStart();
		int total = TemplateStore.getCurrentBook().getContent().length();
		dialog.setIndeterminate(false);
		dialog.incrementProgressBy(start * 100 / total);
		dialog.setX(this.getWindowManager().getDefaultDisplay().getWidth() - 40);
		dialog.setCallBack(new MyProgresDialogCallBack() {
			@Override
			public void callback(int scale) {
				TemplateStore.setCurrentChapter(null);
				TemplateStore.setCurrentChapterSeq(-1);
				TemplateStore.setCurrentPage(null);
				TemplateStore.setPrePage(null);
				TemplateStore.setNextPage(null);
				String content = TemplateStore.getCurrentBook().getContent();
				Log.v("debug", "scale:" + scale);
				if (scale < 0)
					TemplateStore.setCurrentStart(0);
				else if (scale >= 100) {
					String tmpcontent = TemplateStore.getCurrentBook()
							.getContent();
					int start = tmpcontent.length() - 1000;
					start = (start > 0 ? start : 0);
					int offset = TextSplitUtil.getReverseSplitPageOffset(
							tmpcontent.substring(start),
							PageActivity.this.pageView.getWidth(),
							PageActivity.this.pageView.getHeight(),
							TemplateStore.fontSize);
					TemplateStore.setCurrentStart(start + offset);
				} else {
					TemplateStore.setCurrentStart(content.length() * scale
							/ 100);
				}
				TemplateStore.setCurrentEnd(1);
				PageActivity.this.pageView.invalidate();
			}
		});
		return dialog;
	}

	/** 书签集合 */
	private List<BookMark> mBookMarkList = null;
	/** 被选择的书签在集合中的位置 */
	private int bmlocation = 0;
	/** 要操作的书签对象 */
	private BookMark mBookMark = null;

	/**
	 * 浏览书签的view
	 */
	private void bookMarkView() {
		try {
			final Dialog d = new Dialog(this);
			d.setContentView(R.layout.bookmarklist);
			final Button deletebtn = (Button) d.findViewById(R.id.deletebm);
			final Button gobtn = (Button) d.findViewById(R.id.skipbm);
			final Button cancelbtn = (Button) d.findViewById(R.id.cancelbm);
			deletebtn.setVisibility(View.INVISIBLE);
			gobtn.setVisibility(View.INVISIBLE);
			cancelbtn.setVisibility(View.INVISIBLE);
			d.setTitle(getString(R.string.bookmarklist));
			final ListView listv = (ListView) d
					.findViewById(R.id.bookmarklistview);
			mHelper = new CRDBHelper(PageActivity.this.getBaseContext());
			mBookMarkList = mHelper.queryAllBookMark(TemplateStore.getCurrentBook().getId());
			final ListAdapter listAdapter = new ArrayAdapter<BookMark>(this,
					android.R.layout.simple_list_item_1, mBookMarkList);
			listv.setAdapter(listAdapter);
			listv.setSelection(0);
			// 选择一个单元
			listv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int location, long arg3) {
					bmlocation = (int) location;
					mBookMark = mBookMarkList.get(bmlocation);
					skipBookMark(d);
				}
			});
			listv.setOnItemLongClickListener(new ListView.OnItemLongClickListener(){

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int location, long arg3) {
					bmlocation = (int) location;
					mBookMark = mBookMarkList.get(bmlocation);
					deletebtn.setVisibility(View.VISIBLE);
					gobtn.setVisibility(View.VISIBLE);
					cancelbtn.setVisibility(View.VISIBLE);
					return true;
				}
				
			});

			// 删除按钮事件
			deletebtn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {// 删除书签调用
					delBookMark(listv,listAdapter);
				}
			});
			// 跳转按钮事件
			gobtn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
				skipBookMark(d);
				}
			});

			// 取消按钮事件
			cancelbtn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					d.dismiss();
				}
			});
			d.show();
		} catch (Exception e) {
			Toast.makeText(this, e.getStackTrace()[0] + "  " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

	}
	
	private void skipBookMark(Dialog d){
		if (mBookMark != null) {// 开始跳转
			// mTxtReader.readBufferByOffset(mBookMark.getCurrentOffset());
			int offSet = mBookMark.getCurrentOffset();
			TemplateStore.setCurrentChapterSeq(offSet);
			TemplateStore.setPrePage(null);
			TemplateStore.setNextPage(null);
			TemplateStore.setCurrentPage(null);
			TemplateStore.setCurrentStart(offSet);
			PageActivity.this.pageView.postInvalidate();
			d.dismiss();
		}
	}
	private void delBookMark(ListView listv,ListAdapter listAdapter){
		String tag = "delete book mark ";
		Log.v("debug", "removeBookMark:" + mBookMark);
		if (mBookMark != null) {
			Log.d(tag, "start delete book mark");
			boolean b = mHelper.deleteBookMark(mBookMark
					.getBookMarkId());
			if (b && mBookMarkList.size() > 0) {
				mBookMarkList.remove(bmlocation);
				listv.setAdapter(listAdapter);
				mBookMark = null;
				System.gc();
			}
		}
	}

	/**
	 * 旋转屏幕
	 */
	private void circumgyrateScreen() {
		try{
		if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			// 如果是横屏的话，设置为普通模式
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		}catch(Exception e){
			DebugUtil.debug("debug",e);
		}
	}

	/**
	 * 字体设置
	 * */
	int pst = 0;

	private void alertSetting() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Spinner spinner = new Spinner(this);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int postion, long id) {
				pst = postion;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);
		aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		aa.add("12pt");
		aa.add("18pt");
		aa.add("24pt");
		aa.add("30pt");
		spinner.setAdapter(aa);
		builder.setMessage("设置字体大小:").setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						switch (pst) {
						case 0:
							TemplateStore.fontSize = 12;
							break;
						case 1:
							TemplateStore.fontSize = 18;
							break;
						case 2:
							TemplateStore.fontSize = 24;
							break;
						case 3:
							TemplateStore.fontSize = 30;
							break;
						default:
							break;
						}
						TemplateStore.setCurrentPage(null);
						TemplateStore.setPrePage(null);
						TemplateStore.setNextPage(null);
						PageActivity.this.pageView.invalidate();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
					}
				}).setView(spinner);
		AlertDialog alert = builder.create();
		alert.show();
	}

	/**
	 * 保存书签文件view
	 * 
	 * @return 保存成功返回true，否则返回false
	 */
	private void saveBookMarkDialog() {
		try {
			final Dialog d = new Dialog(this);
			d.setTitle(R.string.inputbmname);
			d.setContentView(R.layout.bookmark_dialog);
			final EditText et = (EditText) d.findViewById(R.id.bmet);
			et.setText(pageView.controller.getCurrentPage().getPageContext()
					.subSequence(0, 10));
			final Button sure = (Button) d.findViewById(R.id.bmsure);
			final Button cancel = (Button) d.findViewById(R.id.bmcancel);
			// 确定动作
			sure.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					String bmn = et.getText().toString();
					if (bmn.length() < 1) {
						d.dismiss();
						d.show();
					} else {
						if (bmn.length() > 10) {
							bmn.substring(0, 10);
						}
						BookMark bm = new BookMark();
						bm.setBookId(TemplateStore.getCurrentBook().getId());
						bm.setMarkName(bmn);
						bm.setCurrentOffset(TemplateStore.getCurrentStart());
						bm.setSaveTime(DateUtil.dateToString(new Date()));
						mHelper = new CRDBHelper(PageActivity.this
								.getBaseContext());
						boolean operateResult = mHelper.addBookMark(bm);
						mHelper.close();
						if (operateResult) {
							showDialog(SAVEBOOKMARKSUCCESS);
						} else {
							showDialog(SAVEBOOKMARKFAIL);
						}
						d.dismiss();
					}
				}
			});
			// 取消动作
			cancel.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					d.dismiss();
				}
			});
			d.show();
			System.gc();
		} catch (Exception exp) {
			Toast.makeText(this.getBaseContext(),
					exp.getStackTrace()[0] + "   " + exp.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Intent intent = new Intent(PageActivity.this,NoteActivity.class);
		Bundle bundle = new Bundle();
		switch (item.getItemId()) {
		case PageView.ADDNOTE:
			bundle.putInt("type", 1);
			bundle.putString("title", TemplateStore.getCurrentPage().getPageContext().substring(0, 5));
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case PageView.VIEWNOTE:
			bundle.putInt("type", 2);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

}
